package com.atguigu.yygh.orders.controller;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //根据订单号生成二维码
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable("orderId") Long orderId) {
        Map<String, Object> map = weixinService.createNativeWx(orderId);
        return Result.ok().data(map);

    }


    //根据订单id查询支付状态
    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId") Long orderId) {
        //根据订单查询到微信支付状态接口
        Map<String, String> map = weixinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        if (map == null) {
            throw new YyghException(20001, "支付失败");
        }
        //如果微信支付状态接口返回成功，更新状态
        if ("SUCCESS".equals(map.get("trade_state"))) {
            String out_trade_no = map.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), map);

            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
